package rullekake.beans;

import rullekake.entities.Users;
import rullekake.beans.util.JsfUtil;
import rullekake.facade.UsersFacade;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 * Klasse som håndterer oppretting/visning/endring av brukere og passord
 *
 */


@ManagedBean (name="usersController")
@SessionScoped
public class UsersController {

    private Users current;
    private DataModel items = null;
    @EJB private rullekake.facade.UsersFacade ejbFacade;

    public UsersController() {
    }

    /**
     * Lager nytt objekt hvis det ikke finnes noen fra før, returnerer objektet.
     * @return
     */

    public Users getSelected() {
        if (current == null) {
            current = new Users();
        }
        return current;
    }

    private UsersFacade getFacade() {
        return ejbFacade;
    }

    /**
     * Klargjør liste for visning
     * @return navigation rule
     */
    public String prepareList() {
    //    groupsController.prepareList();
        recreateModel();
        return "users/List";
    }

    /**
     * Setter current til innlogget bruker.
     * @return
     */

    public String prepareChangePassword() {
        current = getFacade().findByUsername(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser());
        return "changepassword";
    }

    /**
     * Klargjør visning av alle bruker
     * @return
     */
    public String prepareView() {
        current = (Users)getItems().getRowData();
        return "users/View";
    }

    /**
     * Klargjør til oppretting av ny bruker
     * @return
     */
    public String prepareCreate() {
//        groupsController.prepareCreate();
        current = new Users();
        return "users/Create";
    }

    /**
     * Oppretter ny bruker
     * @return
     */

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage("UsersCreated");
            recreateModel();
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    /**
     * Klargjør visning av valgt bruker
     * @return
     */

    public String prepareEdit() {
        current = (Users)getItems().getRowData();
        return "users/Edit";
    }

    /**
     * Oppdaterer bruker etter redigering
     * @return
     */

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("UsersUpdated");
            return "mypage";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    /**
     * Henter alle brukere fra database
     * @return
     */

    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    /**
     * Setter items til null, slik at det blir hentet på nytt ved neste getItems-kall
     *
     */

    private void recreateModel() {
        items = null;
    }

    /**
     * Converter
     * 
     */

    @FacesConverter(forClass=Users.class)
    public static class UsersControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UsersController controller = (UsersController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "usersController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Users) {
                Users o = (Users) object;
                return getStringKey(o.getUsername());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+UsersController.class.getName());
            }
        }

    }

}
